<template>
  <div class="guild-manage">
    <h2>公会管理</h2>

    <!-- 搜索和筛选区域 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="6">
        <el-input v-model="searchParams.name" placeholder="公会名称" clearable @keyup.enter="handleSearch" />
      </el-col>
      <el-col :span="6">
        <el-input v-model="searchParams.founderId" placeholder="创始人ID" clearable @keyup.enter="handleSearch" />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-col>
    </el-row>

    <el-table
        :data="guilds.records"
        style="width: 100%"
        border
        @sort-change="handleSortChange"
        :default-sort="{prop: 'id', order: 'descending'}"
    >
      <el-table-column
          prop="id"
          label="ID"
          align="center"
          sortable="custom"
      ></el-table-column>
      <el-table-column
          prop="name"
          label="公会名称"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="description"
          label="公会描述"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="founderId"
          label="创始人ID"
          align="center"
          sortable="custom"
      ></el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          sortable="custom"
      >
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <el-button type="primary" @click="showAddDialog">新增公会</el-button>

    <!-- 新增公会对话框 -->
    <el-dialog title="新增公会" v-model="addDialogVisible" width="30%">
      <el-form :model="newGuild" :rules="rules" ref="addFormRef">
        <el-form-item label="公会名称" prop="name">
          <el-input v-model="newGuild.name"></el-input>
        </el-form-item>
        <el-form-item label="公会描述" prop="description">
          <el-input type="textarea" v-model="newGuild.description"></el-input>
        </el-form-item>
        <el-form-item label="创始人ID" prop="founderId">
          <el-input v-model="newGuild.founderId"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
              v-model="newGuild.createTime"
              type="datetime"
              placeholder="选择创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addGuild">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑公会对话框 -->
    <el-dialog title="编辑公会" v-model="editDialogVisible" width="30%">
      <el-form :model="currentGuild" :rules="rules" ref="editFormRef">
        <el-form-item label="公会名称" prop="name">
          <el-input v-model="currentGuild.name"></el-input>
        </el-form-item>
        <el-form-item label="公会描述" prop="description">
          <el-input type="textarea" v-model="currentGuild.description"></el-input>
        </el-form-item>
        <el-form-item label="创始人ID" prop="founderId">
          <el-input v-model="currentGuild.founderId"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
              v-model="currentGuild.createTime"
              type="datetime"
              placeholder="选择创建时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateGuild">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

// 数据状态
const guilds = ref({ records: [], total: 0 });
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索和排序参数
const searchParams = reactive({
  name: "",
  founderId: "",
  page: 1,
  pageSize: 10,
  sortField: "id",    // 默认排序字段
  sortOrder: "desc"   // 默认排序顺序
});

// 表单数据
const newGuild = ref({
  name: "",
  description: "",
  founderId: "",
  createTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
});
const currentGuild = ref({});
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

// 表单引用
const addFormRef = ref(null);
const editFormRef = ref(null);

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入公会名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入公会描述", trigger: "blur" }],
  founderId: [{ required: true, message: "请输入创始人ID", trigger: "blur" }],
  createTime: [{ required: true, message: "请选择创建时间", trigger: "change" }]
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return "";
  try {
    return dayjs(dateString).format("YYYY-MM-DD HH:mm:ss");
  } catch (e) {
    return "格式错误";
  }
};

// 获取公会列表
const getGuilds = async (params = {}) => {
  try {
    // 合并参数
    const requestParams = {
      page: params.page || page.value,
      pageSize: params.pageSize || pageSize.value,
      sortField: params.sortField || searchParams.sortField,
      sortOrder: params.sortOrder || searchParams.sortOrder,
      name: params.name || searchParams.name,
      founderId: params.founderId || searchParams.founderId
    };

    // 确保请求路径正确（与后端一致）
    const res = await request.get("/guild", { params: requestParams });
    if (res.code === 200) {
      guilds.value = res.data;
      total.value = res.data.total;
      page.value = res.data.page;
      pageSize.value = res.data.rows;
    } else {
      ElMessage.error(res.message || "获取公会列表失败");
    }
  } catch (error) {
    console.error("获取公会列表出错:", error);
    ElMessage.error("网络请求失败，请检查控制台日志");
  }
};

// 页面加载时获取数据
onMounted(() => {
  getGuilds();
});

// 分页大小变更
const handleSizeChange = (val) => {
  pageSize.value = val;
  getGuilds({ page: 1, pageSize: val });
};

// 页码变更
const handleCurrentChange = (val) => {
  page.value = val;
  getGuilds({ page: val });
};

// 搜索功能
const handleSearch = () => {
  searchParams.page = 1;
  getGuilds(searchParams);
};

// 重置搜索
const resetSearch = () => {
  searchParams.name = "";
  searchParams.founderId = "";
  searchParams.sortField = "id";  // 重置排序
  searchParams.sortOrder = "desc";
  handleSearch();
};

// 排序变更处理
const handleSortChange = ({ column, prop, order }) => {
  // 更新排序参数
  if (order) {
    // 确保传递给后端的字段名与数据库字段名一致
    const fieldMapping = {
      founderId: 'founder_id',
      createTime: 'create_time'
    };
    searchParams.sortField = fieldMapping[prop] || prop;
    searchParams.sortOrder = order === "ascending" ? "asc" : "desc";
  } else {
    // 取消排序时恢复默认
    searchParams.sortField = "id";
    searchParams.sortOrder = "desc";
  }

  // 重置页码并获取数据
  page.value = 1;
  getGuilds(searchParams);
};

// 新增公会相关逻辑
const showAddDialog = () => {
  // 默认设置为当前时间
  newGuild.value = {
    name: "",
    description: "",
    founderId: "",
    createTime: dayjs().format("YYYY-MM-DD HH:mm:ss")
  };
  addDialogVisible.value = true;
};

const addGuild = async () => {
  try {
    await addFormRef.value.validate();
    const res = await request.post("/guild", newGuild.value);
    if (res.code === 200) {
      ElMessage.success("新增公会成功");
      await getGuilds({ page: 1 });
      addDialogVisible.value = false;
      newGuild.value = {
        name: "",
        description: "",
        founderId: "",
        createTime: null
      };
    } else {
      ElMessage.error(res.message || "新增公会失败");
    }
  } catch (error) {
    console.error("新增公会出错:", error);
    ElMessage.error("网络请求失败，请检查控制台日志");
  }
};

// 编辑公会相关逻辑
const showEditDialog = (row) => {
  // 确保时间格式正确
  currentGuild.value = {
    ...row,
    createTime: row.createTime ? dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss") : null
  };
  editDialogVisible.value = true;
};

const updateGuild = async () => {
  try {
    await editFormRef.value.validate();
    const res = await request.put("/guild", currentGuild.value);
    if (res.code === 200) {
      ElMessage.success("更新公会成功");
      await getGuilds({ page: page.value });
      editDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || "更新公会失败");
    }
  } catch (error) {
    console.error("更新公会出错:", error);
    ElMessage.error("网络请求失败，请检查控制台日志");
  }
};

// 删除公会相关逻辑
const handleDelete = async (id) => {
  ElMessageBox.confirm(
      "确定要删除该公会吗？此操作不可恢复。",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
  ).then(async () => {
    try {
      const res = await request.delete(`/guild/${id}`);
      if (res.code === 200) {
        ElMessage.success("删除公会成功");
        await getGuilds({ page: page.value });
      } else {
        ElMessage.error(res.message || "删除公会失败");
      }
    } catch (error) {
      console.error("删除公会出错:", error);
      ElMessage.error("网络请求失败，请检查控制台日志");
    }
  }).catch(() => {
    // 取消删除
  });
};
</script>

<style scoped>
.guild-manage {
  padding: 20px;
}
</style>